// composables/useDateFormat.js

export function useDateFormat(timestamp, format = 'YYYY-MM-DD', options = {}) {
  const { relative = false } = options

  // 确保 timestamp 是毫秒级
  const ts = typeof timestamp === 'number'
    ? (timestamp > 10000000000 ? timestamp : timestamp * 1000)
    : 0

  if (ts === 0) {
    return { formatted: '' }
  }

  const now = Date.now()
  const diffMs = ts - now
  const diffSec = Math.floor(diffMs / 1000)
  const diffMin = Math.floor(diffSec / 60)
  const diffHour = Math.floor(diffMin / 60)
  const diffDay = Math.floor(diffHour / 24)

  // 处理未来时间：如果在未来但小于1分钟，显示"刚刚"
  if (relative && diffSec >= 0 && diffSec < 60) {
    return { formatted: '刚刚' }
  }

  // 如果是未来且超过1分钟，使用指定格式
  if (relative && diffSec > 60) {
    return formatDateString(ts, format)
  }

  // 相对时间逻辑（过去时间）
  if (relative) {
    if (diffSec > -60) {
      return { formatted: '刚刚' }
    } else if (diffMin > -60) {
      return { formatted: `${-diffMin}分钟前` }
    } else if (diffHour > -24) {
      return { formatted: `${-diffHour}小时前` }
    } else if (diffDay > -7) {
      return { formatted: `${-diffDay}天前` }
    } else {
      // 超过7天，判断是否超过一个月
      const pastDate = new Date(ts)
      const oneMonthAgo = new Date(now)
      oneMonthAgo.setMonth(oneMonthAgo.getMonth() - 1)

      // 如果早于一个月前，则使用指定格式
      if (pastDate < oneMonthAgo) {
        return formatDateString(ts, format)
      } else {
        return { formatted: `${-diffDay}天前` }
      }
    }
  }

  // 非 relative 模式：使用指定格式
  return formatDateString(ts, format)
}

// 辅助函数：根据格式字符串格式化日期
function formatDateString(timestamp, format) {
  const date = new Date(timestamp)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')

  // 替换格式占位符
  let formatted = format
    .replace(/YYYY/g, year)
    .replace(/MM/g, month)
    .replace(/DD/g, day)
    .replace(/HH/g, hours)
    .replace(/mm/g, minutes)
    .replace(/ss/g, seconds)

  return { formatted }
}